layui.use(['form', 'layer', 'element', 'jquery'], function () {
    window.jQuery = window.$ = layui.jquery;
    var form = layui.form
        , layer = layui.layer
        ,element = layui.element;

    extendForm(form, 'pageForm');
    extendVerify(form);
    checkAll('input.ctrAll')

    //监听提交
    form.on('submit(pageForm)', function (data) {
        app.post($(data.form).attr('action'), data.field,
            function (res) {
                if (res.error != '0') {
                    app.error(res.message);
                } else {
                    var back =  res.url ? res.url : '';
                    if(!back){
                        var page = layui.data('page');
                        back = page.url;
                    }
                    if(!back){
                        window.history.back();
                    }else{
                        app.success(res.message, back);
                    }
                }
            });

        return false;
    });

    //监听多选
    form.on('checkbox', function(data){
    	var filter = $(data.elem).attr('lay-filter');
    	if(data.elem.checked) addCheckValue(filter, data.value);
    	else removeCheckValue(filter, data.value);
    }); 
    form.render();
});

/**
 * 全选
 */
function checkAll(sel) {
    $(sel).on('click', function () {
        var $this = $(this);
        $('input[names='+$this.attr('names')+']').prop('checked', $this.prop('checked'));
    })
}

/**
 * 扩展表单验证
 * @param form layui.form
 */
function extendVerify(form) {
    form.verify({
        length:function (value, item) { //验证长度
            var min = parseInt($(item).attr('minlength'));
            if(min > 0 && value.length < min)  return '长度不能小于' + min;
            var max = parseInt($(item).attr('maxlength'));
            if(max > 0 && value.length > max)  return '长度不能大于' + max;
        }
        ,int:function (value, item) {
            if(!/^[+]?[0-9]+\d*$/i.test(value)) return '只能是数字';
        }
        ,chinese:function(value, item) {
            if(!/^[\u0391-\uFFE5]+$/i.test(value)) return '只能是汉字';
        }
        ,english:function(value, item) {
            if(!/^[A-Za-z]+$/i.test(value)) return '只能是英文';
        }
        ,unnormal:function(value, item) {
            if(!/.+/i.test(value)) return '包含非法字符';
        }
        ,alphanumeric:function(value, item) {
            if(!/^\w+$/i.test(value)) return '只能是字母、数字、下划线';
        }
        ,ip:function(value, item) {
            if(!/d+.d+.d+.d+/i.test(value)) return '非法IP';
        }
        ,same:function(value, item) {
            if(value != $($(item).attr('sames')).val()) return '两次输入不致';
        }
        ,username: function(value, item){ //value：表单的值、item：表单的DOM对象
            if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)){
                return '用户名不能有特殊字符';
            }
            if(/(^\_)|(\__)|(\_+$)/.test(value)){
                return '用户名首尾不能出现下划线\'_\'';
            }
            if(/^\d+\d+\d$/.test(value)){
                return '用户名不能全为数字';
            }
        }
        ,pass: [
            /^[\S]{4,12}$/
            ,'密码必须6到12位，且不能出现空格'
        ]
    });
}

/**
 * 扩展表单元素
 * @param form layui.form
 */
function extendForm(form, filter) {
    var $form = $('form[lay-filter='+filter+']');
    $form.find('select[api]').each(function () {
        initSelect(this, form, filter);
    });

    $form.find('select[tree]').each(function () {
        initSelect(this, form, filter);
    });
}

/**
 * 初始化select选择对象
 * @param ele select对象
 * @param form layui.form
 * @param filter form.lay-filter
 * @param param 取数据的额外参数
 */
function initSelect(ele,  form, filter, param) {
    var $ele = $(ele);
    var api = $ele.attr('api');
    if(!api){
        app.buildSelectTree($ele, $ele.attr('tree'), getDependData(param,  $ele.attr('depend')), buildSelectCallback);
    }else{
        app.buildSelect($ele, api, getDependData(param,  $ele.attr('depend')), buildSelectCallback);
    }

    function getDependData(param, depend) {
        if(typeof param == 'undefined') param = new Object();

        if(typeof depend != 'undefined' && depend!=''){
            var ds = depend.split(',');
            for(var i=0;i<ds.length;i++){
                var $d = $(ds[i]);
                param[$d.attr('name')] = $d.val();
            }
        }

        return param;
    }

    function buildSelectCallback() {
        form.render('select', filter);
        var affect = $ele.attr('affect');
        if(typeof affect != 'undefined' && affect!=''){
            form.on('select('+$ele.attr('lay-filter')+')',function (data) {
                if(affect == 'reload'){
                    window.location =  app.appendLocation($ele.attr('name'), data.value);
                }else{
                    var param = new Object();
                    param[$ele.attr('name')] = data.value;
                    initSelect(affect, form, filter ,param);
                }
            });
        }
    }
}

/**
 * 保存复选框选中的值
 * @param name
 * @param value
 * @returns
 */
function addCheckValue(name, value){
	var $ele = $('#'+name);
    var old = ',' + $ele.val() + ',';
    if(old.indexOf(','+value+',') == -1) old += value+',';
    if(old.substr(0,2) == ',,') old = old.substr(1);
    $ele.val(old.substr(1, old.length-2));
}

/**
 * 删除取消选中的值
 * @param name
 * @param value
 * @returns
 */
function removeCheckValue(name, value){
	var $ele = $('#'+name);
    var old = ',' + $ele.val() + ',';
    if(old.indexOf(','+value+',') == -1) return;
    old = old.replace(value+',', '');
    if(old.substr(0,2) == ',,') old = old.substr(1);
    $ele.val(old.substr(1, old.length-2));
}
